<template>
  <div class="message-list w-[80%] mx-auto" ref="_ref">
    <div
      class="message-item mb-3 w-full"
      v-for="(message, index) in messages"
      :key="index"
    >
      <div
        class="flex w-full"
        :class="{ 'justify-end': message.type === 'question' }"
      >
        <div>
          <div
            class="text-sm text-gray-500 mb-2"
            :class="{ 'text-right': message.type === 'question' }"
          >
            {{ message.createdAt }}
          </div>
          <div v-if="message.type === 'question'">
            <div class="mb-3 flex justify-end">
              <img
                v-if="message.imagePath"
                :src="`safe-file://${message.imagePath}`"
                alt="提问的配图"
                class="h-24 w-24 object-cover rounded"
              />
            </div>
            <div
              class="message-question bg-green-700 text-white p-2 rounded-md"
            >
              {{ message.content }}
            </div>
          </div>
          <div
            class="message-answer p-2 rounded-md"
            v-else
            :class="{
              'bg-red-100 text-red-700': message.status === 'error',
            }"
          >
            <template v-if="message.status === 'loading'">
              <Icon icon="eos-icons:three-dots-loading"></Icon>
            </template>
            <template v-else-if="message.status === 'error'">
              <span>{{ message.content }}</span>
            </template>
            <div
              v-else
              class="prose prose-slate prose-hr:hidden prose-li:my-0 prose-ul:my-3 prose-p:my-1 prose-pre:p-0"
            >
              <vue-markdown :source="message.content" :plugins="plugins" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Icon } from "@iconify/vue";
import { MessageProps } from "../types";
import VueMarkdown from "vue-markdown-render";
import markdownItHighlightjs from "markdown-it-highlightjs";

const plugins = [markdownItHighlightjs];

defineProps<{ messages: MessageProps[] }>();

const _ref = ref<HTMLDivElement>();

defineExpose({
  ref: _ref,
});
</script>

<style scoped>
.message-question {
  word-break: break-all;
}
</style>
